package com.ztx.web.controller.sys;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ztx.model.RoleVO;
import com.ztx.pagemodel.easyui.DataGrid;
import com.ztx.pagemodel.easyui.Json;
import com.ztx.pagemodel.easyui.PageHelper;
import com.ztx.pagemodel.easyui.Tree;
import com.ztx.service.base.IBaseService;
import com.ztx.service.user.IRoleService;
import com.ztx.service.user.IUserService;

@Controller
@RequestMapping("roleController")
public class RoleController {

	private static final Logger log = LoggerFactory
			.getLogger(RoleController.class);
	@Resource
	private IUserService userService = null;
	@Resource
	private IBaseService baseService = null;

	@Resource
	private IRoleService roleService = null;

	/** 跳转到角色管理页面 */
	@RequestMapping("/manager")
	public String manager() {
		return "admin/role";
	}

	/**
	 * 角色列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "datagrid")
	@ResponseBody
	public DataGrid<RoleVO> datagrid(PageHelper ph, RoleVO role) {

		return userService.roleDataGrid(ph, role);
	}

	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String addRole() {
		return "admin/addrole";
	}

	/** 添加角色 */
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public Json addRole(RoleVO role) {
		Json json = new Json();
		try {
			baseService.add(RoleVO.class.getName() + ".addRole", role);
			json.setMsg("操作成功");
		} catch (Exception e) {
			json.setSuccess(false);
			json.setMsg(e.getMessage());
		}
		return json;
	}

	/**
	 * 根据角色id查询该角色拥有的资源
	 * 
	 * @param roleId
	 * @return
	 */
	@RequestMapping(value = "getResource", method = RequestMethod.POST)
	@ResponseBody
	public List<Tree> queryResource(String roleId) {
		List<Tree> tree = null;
		try {
			tree = roleService.queryResourceByRoleId(roleId);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return tree;

	}

	/** 角色授权,保存数据 */
	@RequestMapping(value = "addResourceRole", method = RequestMethod.POST)
	@ResponseBody
	public Json addResourceRole(String roleId, String[] resIds) {
		Json json = new Json();
		try {
			roleService.addResourceRole(roleId, resIds);
		} catch (Exception e) {
			log.error("保存角色资源关系失败",e);
			json.setSuccess(false);
			json.setMsg(e.getMessage());
		}
		return json;
	}

}
